Apache2 Single Page Application
Pre-Requisites
To route all requests to a single HTML/PHP page, mod-rewrite must be enabled.
sudo a2enmod rewrite
Restart the Apache2 service afterwards for the changes to take effect.
# Older Debian Systems
sudo service apache2 restart
# Newer Debian Systems
sudo systemctl restart apache2
vhost Configuration
Rewrite configuration may be defined in the vhost file.
<Directory "/var/www/html">
Order allow,deny
Allow from all
Require all granted
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) /index.html [NC,L]
</Directory>
Restart the Apache2 service afterwards for the changes to take effect.
# Older Debian Systems
sudo service apache2 restart
# Newer Debian Systems
sudo systemctl restart apache2
htaccess Configuration
Apache2 doesn't read .htaccess files by default. Modify the vhost file to enable it.
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
Require all granted
</Directory>
Rewrite configuration may be defined in the .htaccess file.
<IfModule mod_rewrite.c>
RewriteEngine On
#RewriteBase /
# skip existing files
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule index.html - [QSA,L,C]
RewriteRule .* - [QSA,L]
# deny access php files
RewriteCond %{REQUEST_URI} ^.*\.php$
RewriteRule ^(.*)$ index.html [QSA,L]
# assets
RewriteCond %{REQUEST_URI} ^assets/*$
RewriteRule ^assets/*$ - [QSA,L]
# redirect root access (/) to index.html
#RewriteCond %{REQUEST_URI} ^/$
#RewriteRule ^$ index.html [QSA,L]
# redirect 404 for non existent files
RewriteCond %{REQUEST_URI} ^(.*)\..*$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.html [QSA,L]
# default, redirect to our front web controller
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.html [QSA,L]
</IfModule>